package com.xcc.dataStructures.demo04_stack;

import java.util.Arrays;
import java.util.List;

/**
 * 逆波兰表达式(实现计算器后缀表达)
 *
 * @author xiaocheng
 * @date 2020/11/26 17:03
 */
public class RePolishDemo {

    public static void main(String[] args) {
        //"30 4 + 5 * 6 -
        String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";
        //将原始表达式存储到list中
        List<String> ls = getExpressionList(suffixExpression);
        System.out.println(ls);
        int res = cal(ls);
        System.out.println("res = " + res);
    }

    /**
     * 计算list
     */
    private static int cal(List<String> ls) {
        ArrayStack nums = new ArrayStack(10);
        for (String s : ls) {
            if (s.matches("\\d+")) {
                //数值直接入栈
                nums.push(Integer.parseInt(s));
            }else {
                //如果是符合则取出两个符号和数值计算之后的  结果再入栈
                int num2 = nums.pop();
                int num1 = nums.pop();
                int cal = nums.cal(num1, num2, s.charAt(0));
                //计算结果入栈
                nums.push(cal);
            }
        }
        return nums.pop();
    }

    /**
     * 将原始表达式存储到list中
     */
    private static List<String> getExpressionList(String suffixExpression) {
        String[] split = suffixExpression.split(" ");
        return Arrays.asList(split);
    }

}
